#!/usr/bin/python3
# -*- coding=utf-8 -*-

import time

TIME_BIT_COUNT = 42
WORK_BIT_COUNT = 10
SERIAL_BIT_COUNT = 12

class UniqueNumber:
    # // time // workId // serial
    def __init__(self, workId):
        self.serial = 0
        self.workId = workId
        self.lastTime = 0
        self.__MaxSerial = 1 << SERIAL_BIT_COUNT

    def getId(self):
        now = int(time.time())
        if (self.lastTime == now):
            self.serial += 1
        else:
            self.serial = 0
            self.lastTime = now

        if self.serial >= self.__MaxSerial:
            time.sleep(0.5)
            return self.getId()

        serial = self.serial & ((1 << SERIAL_BIT_COUNT) - 1)
        workId = (self.workId & ((1 << WORK_BIT_COUNT) - 1)) << SERIAL_BIT_COUNT
        timeSeq = (self.lastTime & ((1 << TIME_BIT_COUNT) - 1)) << (WORK_BIT_COUNT + SERIAL_BIT_COUNT)

        # print(self.serial, self.workId, self.lastTime)
        # print(bin(serial))
        # print(bin(workId))
        # print(bin(timeSeq))

        return serial | workId | timeSeq

    def __str__(self):
        return 'UniqueNumber({})'.format(self.workId)


def main():
    numGen = UniqueNumber(20)
    print(str(numGen))
    for item in xrange(10):
        number = numGen.getId()
        print(hex(number), number)
        print('%0x' %number)



if __name__ == '__main__' :
    main()
